import java.io.*;
import java.net.Socket;
import java.net.URLDecoder;
import java.nio.file.Files;
import java.util.Date;

/**
 * @author Benny
 * 
 * */

public class WebServer extends Thread {

	private File _rootDir;
	private Socket _socket;

	public WebServer(Socket socket, File rootDir) {
		_socket = socket;
		_rootDir = rootDir;
	}

	private static void sendHeader(BufferedOutputStream out, int code,
			String contentType, long contentLength, long lastModified)
			throws IOException {
		out.write(("HTTP/1.0 "
				+ code
				+ " OK\r\n"
				+ "Date: "
				+ new Date().toString()
				+ "\r\n"
				+ "Server: MyWebServer\r\n"
				+ "Content-Type: "
				+ contentType
				+ "\r\n"
				+ "Expires: Thu, 01 Dec 1994 16:00:00 GMT\r\n"
				+ ((contentLength != -1) ? "Content-Length: " + contentLength
						+ "\r\n" : "") + "Last-modified: "
				+ new Date(lastModified).toString() + "\r\n" + "\r\n")
				.getBytes());
	}

	private static void sendError(BufferedOutputStream out, int code,
			String message) throws IOException {
		sendHeader(out, code, "text/html", message.length(),
				System.currentTimeMillis());
		out.write(message.getBytes());
		out.flush();
		out.close();
	}

	public void run() {
		InputStream reader = null;
		try {
			BufferedReader in = new BufferedReader(new InputStreamReader(
					_socket.getInputStream()));
			BufferedOutputStream out = new BufferedOutputStream(
					_socket.getOutputStream());

			String request = in.readLine();
			if (request == null || !request.startsWith("GET ")) { // Invalid
																	// request
																	// type (no
																	// "GET")
				sendError(out, 500, "Invalid Method.");
				return;
			}

			String path = request.substring(4, request.length() - 9); //request adresse
			File file = new File(_rootDir, URLDecoder.decode(path, "UTF-8"))
					.getCanonicalFile();
			// }

			if (file.isDirectory()) { // check for index in the file
				File indexFile = new File(file, "index.html");
				if (indexFile.exists() && !indexFile.isDirectory()) {
					file = indexFile;
				}
			}
			// }

			if (!file.toString().startsWith(_rootDir.toString())) { // outside
																	// of our
																	// web root
																	// directory.
				sendError(out, 403, "Permission Denied.");
			} else if (!file.exists()) { // The file was not found.
				sendError(out, 404, "File Not Found.");
			} else {
				reader = new BufferedInputStream(new FileInputStream(file));

				String contentType = file.toURL().openConnection()
						.getContentType(); //filetype

				sendHeader(out, 200, contentType, file.length(),
						file.lastModified());

				byte[] buffer = new byte[4096];
				int bytesRead;
				while ((bytesRead = reader.read(buffer)) != -1) {
					out.write(buffer, 0, bytesRead);
				}
				reader.close();
			}
			out.flush();
			out.close();
		} catch (IOException e) {
			if (reader != null) {
				try {
					reader.close();
				} catch (Exception any) { // Do nothing.
				}
			}
		}
	}
}
